package com.chinaoryx.generator;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Writer;

public class ScriptGenerator {
	
	static final String LINE_BREAKER = "\r\n";
	
	
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ScriptGenerator.class);
	
	
	public void generateBat(String basedir, Writer out) throws IOException{
		
		this.writeBatVariable(out);
		
		
		File basedirFile = new File(basedir);
		if (!basedirFile.isDirectory()) {
			return;
		}
		
		File[] files = basedirFile.listFiles(new FileFilterImpl());
		for (File file : files) {
			if (file.isDirectory()) {
				this.readDir(file, out);
			} else if (file.isFile()){
				this.writeForSingleFile(out, file);
//				logger.info(file);
			}
		}
		
	}
	
	
	private void readDir(File dir, Writer out) throws IOException{
		File[] files = dir.listFiles(new FileFilterImpl());
		for (File file : files) {
			if (file.isDirectory()) {
				this.readDir(file, out);
			} else if (file.isFile()) {
				this.writeForSingleFile(out, file);
//				logger.info(file);
			}
		}
	}
	
	
	private void writeBatVariable(Writer out) throws IOException{
		
		out.write("@echo off");
		out.write(LINE_BREAKER);
		
		out.write("set DB_SERVER=havi-server");
		out.write(LINE_BREAKER);
		
		out.write("set DB_USER=lsos");
		out.write(LINE_BREAKER);
		
		out.write("set DB_PWD=lsos");
		out.write(LINE_BREAKER);
		
		out.write("set DB_NAME=lsos_prod");
		out.write(LINE_BREAKER);
		
		out.write("set FILE_CHARSET=utf8");		
		out.write(LINE_BREAKER);		
		
		out.write("set PORT=3306");		
		out.write(LINE_BREAKER);
		
		out.write("echo start... > log.txt");		
		out.write(LINE_BREAKER);
	}
	
	
	private void writeForSingleFile(Writer out, File file) throws IOException{
		String filename = file.getPath();
		
		out.write("echo ***************************************>> log.txt");
		out.write(LINE_BREAKER);
		
		out.write("echo execute \"" + filename + "\" start >>log.txt");
		out.write(LINE_BREAKER);
		
		out.write("if not exist \""+ filename +"\"    echo \"file not found\" >> log.txt");
		out.write(LINE_BREAKER);
		
		out.write("mysql --host=%DB_SERVER% --port=%PORT% --user=%DB_USER% --password=%DB_PWD% --database=%DB_NAME% --comments --default-character-set=%FILE_CHARSET% < \""+ filename +"\" >>log.txt 2>&1");
		out.write(LINE_BREAKER);
		
				
		out.write("echo execute \"" + filename + "\" end >>log.txt");
		out.write(LINE_BREAKER);
	}
	
	
	
	class FileFilterImpl implements FileFilter{

		public boolean accept(File pathname) {
			if (pathname.isHidden()){
				return false;
			}
			
			if (pathname.isFile()) {
				if (pathname.getName().endsWith(".sql")){
					return true;
				}
				else {
					return false;
				}				
			}
			
			return true;
		}
				
	}

}
